const models = require('./../db/mysqldb/index')
const {
  ErrorModel,
  encrypt,
  SuccessModel,
  validate
} = require('./../utils/index')
const { saltTime } = require('./../config/index')
const logger = require('./../utils/logger')
const svgCaptcha = require('svg-captcha')
const jwt = require('jsonwebtoken')
const config = require('./../config/index')
const { Op } = require("sequelize");

class SysUserController {
  /**
   * @description 获取验证码
   * @param {*} req
   * @param {*} res
   */
  static async getCode (req, res) {
    const codeConfig = {
      size: 2,
      ignoreChars: '0o1i',
      noise: 1,
      color: true,
      // 宽度
      width: 100,
      // 高度
      height: 34,
      background: '#cc9966'
    }
    let captcha = svgCaptcha.createMathExpr(codeConfig)
    req.session.captcha = captcha.text.toLocaleLowerCase()
    res.json(new SuccessModel({ data: { text: captcha.text, result: captcha.data } }))
  }
  /**
   * @description 登陆
   * @param {*} username
   * @param {*} password
   * @param {*} captcha
   */
  static async login (req, res, next) {
    const { username, password, captcha } = req.body
    logger.info(`SysUserController`, 'login', `req.body`, req.body)
    if (!captcha) {
      res.json(new ErrorModel([], `请输入验证码`))
      return
    }
    if (!username || !password) {
      res.json(new ErrorModel([], `请输入用户名或密码`))
      return
    }
    try {
      const sessionCaptcha = req.session.captcha
      if (sessionCaptcha !== captcha) {
        res.json(new ErrorModel([], `验证码错误`))
        return
      }
      const user = await models.sys_user.findOne({
        where: {
          username
        }
      })
      logger.info(`SysUserController`, 'login', `user`, user)
      if (!user) {
        res.json(new ErrorModel([], `用户不存在`))
        return
      }
      const opassword = await validate(password, user.password)
      if (!opassword) {
        res.json(new ErrorModel([], `密码错误`))
        return
      }
      if (user.delete_timestamp) {
        res.json(new ErrorModel([], `禁止登录，请联系管理员！`))
        return
      }
      let datas = {
        user_id: user.user_id,
        avatar: user.avatar,
        phone: user.phone,
        realname: user.realname,
        sex: user.sex,
        username,
      }
      logger.info(datas)
      jwt.sign(
        datas,
        config.secretOrKey,
        // 设置过期时间
        { expiresIn: 60 * 60 * 24 },
        (err, token) => {
          if (err) {
            logger.info(`SysUserController`, 'login', `jwt-err`, err)
            res.json(new ErrorModel([], err.message))
          } else {
            logger.info(`SysUserController`, 'login', `jwt-token`, token)
            res.json(
              new SuccessModel(
                { token: token, isLogin: true, ...datas },
                '登录成功'
              )
            )
          }
        }
      )
    } catch (error) {
      logger.error(`SysUserController`, 'login', `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
 * @description 退出登陆
 * @param {*} username
 * @param {*} password
 * @param {*} captcha
 */
  static async logout (req, res, next) {
    try {
      req.headers['authorization'] = ""
      res.json(new SuccessModel([], "sucess"))
    } catch (error) {
      logger.error(`SysUserController`, 'login', `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 添加用户
   * @param {*} username
   * @param {*} realname
   * @param {*} phone
   */
  static async userAdd (req, res, next) {
    const { username, realname, phone, remark } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`SysUserController`, `userAdd`, `req.body`, req.body)
    if (!username) {
      res.json(new ErrorModel([], `请输入用户名或密码`))
      return
    }
    const userInfo = await models.sys_user.findOne({
      where: {
        username,
        delete_timestamp: {
          [Op.is]: null,
        }
      }
    })
    if (userInfo) {
      res.json(new ErrorModel([], `用户已存在`))
      return
    }
    try {
      const npassword = await encrypt(config.defaultpassword, saltTime)
      logger.info(`SysUserController`, `userAdd`, `npassword`, npassword)
      const result = await models.sys_user.create({
        username,
        password: npassword,
        realname,
        phone,
        remark,
        create_by: op_user_id
      })
      logger.info(`SysUserController`, `userAdd`, `result`, result)
      res.json(new SuccessModel([], `新增用户成功`))
    } catch (error) {
      logger.error(`SysUserController`, `userAdd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 更新用户
   * @param {*} user_id
   * @param {*} username
   * @param {*} realname
   * @param {*} phone
   * @param {*} remark
   */
  static async userUpd (req, res, next) {
    const { user_id, username, realname, phone, remark } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`SysUserController`, `userUpd`, `req.body`, req.body)
    if (!user_id) {
      res.json(new ErrorModel([], `请输入必填项`))
      return
    }
    try {
      const userInfo = await models.sys_user.findOne({
        where: {
          username,
          delete_timestamp: {
            [Op.is]: null,
          },
          user_id: {
            [Op.ne]: user_id,
          }
        }
      })
      if (userInfo) {
        res.json(new ErrorModel([], `用户已存在`))
        return
      }
      const result = await models.sys_user.update(
        {
          username,
          realname,
          phone,
          remark,
          update_by: op_user_id,
          update_timestamp: Date.now()
        },
        {
          where: { user_id }
        }
      )
      logger.info(`SysUserController`, `userUpd`, `result`, result)
      res.json(new SuccessModel([], `用户更新成功`))
    } catch (error) {
      logger.error(`SysUserController`, `userUpd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 删除用户
   * @param {*} user_id
   */
  static async userDel (req, res, next) {
    const { user_id } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`SysUserController`, `userDel`, `req.body`, req.body)
    if (!user_id) {
      res.json(new ErrorModel([], `user_id 获取失败`))
      return
    }
    try {
      const result = await models.sys_user.update(
        {
          delete_timestamp: Date.now(),
          delete_by: op_user_id
        },
        {
          where: { user_id }
        }
      )
      logger.info(`SysUserController`, `userDel`, `result`, result)
      res.json(new SuccessModel([], `删除用户成功`))
    } catch (error) {
      logger.error(`SysUserController`, `userDel`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 修改密码
   * @param {*} password
   * @param {*} newPassword
   */
  static async modifypwd (req, res, next) {
    const { password, newPassword } = req.body
    const { user_id } = req.user
    logger.info('modifypwd', `req.body`, req.body)
    if (!password) {
      res.json(new ErrorModel([], `请输入密码`))
      return
    }
    try {
      // @todo 修改密码 验证有问题
      const userInfo = await models.sys_user.findOne({
        where: {
          user_id,
          delete_timestamp: {
            [Op.is]: null,
          }
        }
      })
      if (!userInfo) {
        res.json(new ErrorModel([], `用户不存在`))
        return
      }
      const vf = await validate(password, userInfo.password)
      logger.info('modifypwd', `vf`, vf)
      if (vf) {
        const npassword = await encrypt(newPassword, saltTime)
        logger.info('modifypwd', `npassword`, npassword)
        const updateInfo = await models.sys_user.update(
          {
            password: npassword
          },
          {
            where: {
              user_id
            }
          }
        )
        logger.info('modifypwd', `updateInfo`, updateInfo)
        res.json(new SuccessModel([], `更新成功`))
      } else {
        res.json(new ErrorModel([], "原密码错误"))
      }
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   * @description 查找用户
   * @param {*} name
   */
  static async findUserByName (req, res, next) {
    const { realname } = req.body
    const { user_id } = req.user
    try {
      let sql = `SELECT user_id ,realname ,sex,avatar FROM sys_user WHERE (realname like "%${realname}%" or username like "%${realname}%") and delete_timestamp is null and user_id != ${user_id}`
      const result = await models.sequelize.query(sql, {
        replacements: ['active'],
        type: models.sequelize.QueryTypes.SELECT,
      })
      res.json(new SuccessModel(result, "success"))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   * @description 查找用户 通过id
   * @param {*} name
   */
  static async getUserInfo (req, res, next) {
    const { user_id } = req.body
    try {
      let sql = `SELECT user_id ,realname ,sex,avatar FROM sys_user WHERE user_id = ${user_id} and delete_timestamp is null`
      const result = await models.sequelize.query(sql, {
        replacements: ['active'],
        type: models.sequelize.QueryTypes.SELECT,
      })
      res.json(new SuccessModel(result, "success"))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }
}

module.exports = {
  SysUserController
}
